module IPFS.Client.Command.Block (
 stat,
 get,
 StatInfo(..)
) where

import Prelude

import Data.Argonaut (class DecodeJson, Json, decodeJson, fromString)
import Data.Argonaut.Decode ((.:))
import Data.Either (Either)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
import Data.Maybe (Maybe(..))
import Effect.Aff (Aff)
import Foreign.Object as O
import IPFS.Client (Client)
import IPFS.Client.Command (Command, defCommand)
import IPFS.Client.Utils.SendRequest (execBufferCommand, execJsonCommand)
import Node.Buffer (Buffer)

hashCommand::String -> String -> Command
hashCommand apiPath hash = defCommand {path = apiPath , args = Just [fromString hash],qs = O.empty }
------------------------stat---------------------------------
newtype StatInfo = StatInfo {
 key::String,
 size::Int
}

derive instance genericStatInfo :: Generic StatInfo _
instance showStatInfo :: Show StatInfo where
  show s = genericShow s

instance decodeJsonStatInfo :: DecodeJson StatInfo where
  decodeJson::Json -> Either String StatInfo
  decodeJson json = do
   dJson <- decodeJson json
   k <- dJson .: "Key"
   s <- dJson .: "Size"
   pure $ StatInfo { key:k , size:s }

stat::Client -> String -> Aff (Either String StatInfo)
stat client hash = execJsonCommand client $ hashCommand "block/stat" hash

------------------------get---------------------------------
get::Client -> String -> Aff (Either String Buffer)
get client hash = execBufferCommand client $ hashCommand "block/get" hash

